package com.bobo.filter;

import com.bobo.model.Admin;
import com.bobo.model.User;
import org.apache.commons.logging.Log;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;

/**
 * Created by bobo on 2016/9/27.
 * filter
 */
public class LoginFilter implements Filter {

    private FilterConfig config;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        config = filterConfig;
        System.out.println("登录拦截器已经启动");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //设置编码格式
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        HttpSession session = request.getSession();

        String[] noFilter = config.getInitParameter("LoginPaths").split(";");

        //不需要拦截的路径 (静态资源)
        for (String aNoFilter : noFilter) {
            if (request.getRequestURI().endsWith(aNoFilter)) {
                filterChain.doFilter(request, response);
                return;
            }
        }

        //前台需要拦截的路径
        String[] needFilter = config.getInitParameter("needLoginPaths").split(";");
        for (String aNoFilter : needFilter) {
            if (request.getRequestURI().startsWith(aNoFilter)&&session.getAttribute("user") == null) {
                response.sendRedirect("/login/login");
                return;
            }
        }

        // 后台登陆拦截
        if(request.getRequestURI().startsWith("/admin") && session.getAttribute("admin") == null) {
            response.sendRedirect("/back/login");
            return;

        }
        filterChain.doFilter(request, response);

    }

    @Override
    public void destroy() {
        System.out.println("登录拦截器已经销毁");
    }
}
